#include "storedialog.h"
#include "ui_storedialog.h"

#include <QSqlTableModel>

StoreDialog::StoreDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::StoreDialog)
{
    ui->setupUi(this);
    this->loadData();
}

StoreDialog::~StoreDialog()
{
    delete ui;
}

QString StoreDialog::getStore() const
{
    return ui->store_lineEdit->text();
}

QString StoreDialog::getNote() const
{
    return ui->note_textEdit->toPlainText();
}

QString StoreDialog::getOperator() const
{
    return ui->operator_comboBox->currentText();
}

int StoreDialog::getOperatorId() const
{
    QSqlTableModel *model = qobject_cast<QSqlTableModel *>(ui->operator_comboBox->model());
    if(model){
        QString field("id");
        return model->data(model->index(ui->operator_comboBox->currentIndex(), model->fieldIndex(field))).toInt();
    }
    return -1;
}

void StoreDialog::accept()
{
    if(ui->store_lineEdit->text().isEmpty() || ui->operator_comboBox->currentText().isEmpty())
        return;
    QDialog::accept();
}

void StoreDialog::setStore(const int store_id)
{
    setWindowTitle(tr("Store (edit)"));
    QSqlTableModel *model = new QSqlTableModel(this);
    model->setTable("stores");
    model->select();

    QModelIndexList item = model->match(model->index( 0, model->fieldIndex("id")), Qt::DisplayRole, store_id,  1, Qt::MatchExactly);

    ui->store_lineEdit->setText(model->data(model->index(item[0].row(), model->fieldIndex("store"))).toString());
    ui->note_textEdit->setText(model->data(model->index(item[0].row(), model->fieldIndex("note"))).toString());
    int operator_id = model->data(model->index(item[0].row(), model->fieldIndex("operator_id"))).toInt();
    this->setOperator(operator_id);
}

void StoreDialog::setOperator(const int operator_id)
{
    QSqlTableModel *model = qobject_cast<QSqlTableModel *>(ui->operator_comboBox->model());
    if(model){
        QModelIndexList Operators = model->match(model->index( 0, model->fieldIndex("id")), Qt::DisplayRole, operator_id,  1, Qt::MatchExactly);
        ui->operator_comboBox->setCurrentIndex(Operators[0].row());
    }
}

void StoreDialog::loadData()
{
    QSqlTableModel *model = new QSqlTableModel(ui->operator_comboBox);
    model->setTable("operators");
    model->select();

    ui->operator_comboBox->setModel(model);
    ui->operator_comboBox->setModelColumn(model->fieldIndex("name"));
    ui->operator_comboBox->setCurrentIndex(0);
}
